package com.google.code.cisx.client.gadgets.deprecated;

import com.google.code.cisx.client.GoogleFeedRequest;
import com.google.code.cisx.client.GoogleFeedRequestHandler;
import com.google.code.cisx.client.model.Gadget;
import com.google.code.cisx.client.model.GadgetClass;
import com.google.code.cisx.client.model.UserPref;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.HTML;

public class WeatherGadget extends Gadget implements GoogleFeedRequestHandler {

  public static class Class extends GadgetClass {
    public static UserPref location = new UserPref("Location", "10001");

    public Class() {
      super("Weather", true);
      addUserPref(location);
    }

    public Gadget newGadget() {
      return new WeatherGadget(this);
    }
  }

  private HTML body = new HTML();

  protected WeatherGadget(Class c) {
    super(c);
    initWidget(body);
    setStyleName("Weather");
    refresh();
  }

  public void refresh() {
    body.setHTML("");
    String url = "http://xml.weather.yahoo.com/forecastrss?p=" + getUserPrefValue(Class.location);
    GoogleFeedRequest.get(url, this);
  }

  public void onRequestComplete(String result) {
    JSONObject feed = (JSONObject) JSONParser.parse(result);
    JSONArray entries = (JSONArray) feed.get("entries");
    if (entries.size() > 0) {
      JSONObject item = (JSONObject) entries.get(0);
      JSONString content = (JSONString) item.get("content");
      body.setHTML(content.stringValue());
    }
  }

  public void onRequestFailed(String error) {
    body.setHTML(error);
  }

}